package com.rainsoft.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author 13646223842@163.com
 * @since 1.0.0
 * 2015/11/13.
 */
public class DBUtil {
    //数据库配置
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "";
    private static final String username = "";
    private static final String password = "";

    //定义一个用于放置数据库连接的局部线程变量(每个线程都有自己的连接)
    private static ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>();

    //获取连接
    public static Connection getConnection() {
        Connection conn = connContainer.get();
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭连接
    public static void closeConnection() {
        Connection conn = connContainer.get();
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            connContainer.remove();
        }
    }

}
